/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormPelanggan.java
 *
 * Created on Jan 30, 2011, 7:05:01 PM
 */

package juwita;

import config.DBConnection;
import java.sql.*;
//import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;
/**
 *
 * @author Abah
 */
public class FormPelanggan extends javax.swing.JInternalFrame {

    private DefaultTableModel DftTabMode;
    java.sql.Connection conn = new DBConnection().connect();
    
    /** Creates new form FormPelanggan */
    public FormPelanggan() {
        initComponents();
        btnEdit.setEnabled(false);
        btnDelete.setEnabled(false);

        tampilData();
        setKdPlg();
       
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnTengah = new javax.swing.JPanel();
        spPlg = new javax.swing.JScrollPane();
        tbPlg = new javax.swing.JTable();
        pnAtas = new javax.swing.JPanel();
        btnDelete = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        txtNamaPlg = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtKdPlg = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAlamat = new javax.swing.JTextArea();
        btnShowAll = new javax.swing.JButton();
        txtSearch = new javax.swing.JTextField();
        btnNew = new javax.swing.JButton();
        cbSearch = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtHp = new javax.swing.JTextField();
        txtTelp = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        cbJk = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Data Pelanggan");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/pelanggan.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        pnTengah.setBackground(new java.awt.Color(255, 255, 255));
        pnTengah.setLayout(new java.awt.BorderLayout());

        tbPlg.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbPlg.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbPlgMousePressed(evt);
            }
        });
        tbPlg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbPlgKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbPlgKeyReleased(evt);
            }
        });
        spPlg.setViewportView(tbPlg);

        pnTengah.add(spPlg, java.awt.BorderLayout.CENTER);

        pnAtas.setBackground(new java.awt.Color(255, 255, 255));
        pnAtas.setMinimumSize(new java.awt.Dimension(400, 273));
        pnAtas.setPreferredSize(new java.awt.Dimension(410, 280));
        pnAtas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        pnAtas.add(btnDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 130, 70, 20));

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        pnAtas.add(btnEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 100, 70, -1));
        pnAtas.add(txtNamaPlg, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, 300, -1));

        jLabel2.setText("Jenis Kel");
        pnAtas.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, 20));

        txtKdPlg.setEditable(false);
        txtKdPlg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtKdPlgKeyReleased(evt);
            }
        });
        pnAtas.add(txtKdPlg, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 61, -1));

        jLabel3.setText("Kode Plg");
        pnAtas.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        jLabel4.setText("Handphone");
        pnAtas.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, -1, -1));

        txtAlamat.setColumns(20);
        txtAlamat.setRows(5);
        jScrollPane1.setViewportView(txtAlamat);

        pnAtas.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 160, 220, 50));

        btnShowAll.setText("Show All");
        btnShowAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowAllActionPerformed(evt);
            }
        });
        pnAtas.add(btnShowAll, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, 80, -1));
        pnAtas.add(txtSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 230, 190, -1));

        btnNew.setText("New");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        pnAtas.add(btnNew, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 70, 70, -1));

        cbSearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kode Plg", "Namal" }));
        pnAtas.add(cbSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 80, -1));

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        pnAtas.add(btnSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 250, 70, -1));

        jLabel5.setText("Alamat");
        pnAtas.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 160, -1, -1));
        pnAtas.add(txtHp, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 130, 160, -1));
        pnAtas.add(txtTelp, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 100, 160, -1));

        jLabel6.setText("Telp");
        pnAtas.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, -1, -1));

        cbJk.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pria", "Wanita" }));
        pnAtas.add(cbJk, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 70, 70, -1));

        jLabel7.setText("Nama Plg");
        pnAtas.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, 20));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/p_plg.png"))); // NOI18N
        pnAtas.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 180, -1, -1));

        pnTengah.add(pnAtas, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(pnTengah, java.awt.BorderLayout.CENTER);

        setBounds(0, 0, 420, 409);
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // TODO add your handling code here:
        int clossing;
        clossing = JOptionPane.showConfirmDialog(this,
                "Tutup Data Pelanggan?",
                "Konfirmasi",
                JOptionPane.YES_NO_OPTION);
        if (clossing == 0){
            this.dispose();
            FormMain.isfPel = false;
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void tbPlgMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPlgMousePressed
        getDataFromTable();
}//GEN-LAST:event_tbPlgMousePressed

    private void tbPlgKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbPlgKeyPressed
        // TODO add your handling code here:
        getDataFromTable();
}//GEN-LAST:event_tbPlgKeyPressed

    private void tbPlgKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbPlgKeyReleased
        // TODO add your handling code here:
        getDataFromTable();
}//GEN-LAST:event_tbPlgKeyReleased

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if(btnDelete.getText().equals("Cancel")){
            kosongkan();
            tampilData();
        }else if(btnDelete.getText().equals("Delete")){
            deleteData();
        }

        //*
        //*/
}//GEN-LAST:event_btnDeleteActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        // TODO add your handling code here:
        //BARU KOPAS
        if(btnEdit.getText().equals("Save")){
            if(txtNamaPlg.getText().equals("")) {
                JOptionPane.showMessageDialog(this, "Nama Pelanggan harus diisi!",
                        "Informasi",JOptionPane.INFORMATION_MESSAGE);
            }else{
                if(txtTelp.getText().equals("") || txtHp.getText().equals("") ) {
                    JOptionPane.showMessageDialog(this, "Kontak no (telp/hp) harus diisi!",
                            "Informasi",JOptionPane.INFORMATION_MESSAGE);
                }else{

                    if(isDuplicatePKey()==true){
                        kosongkanNew();
                        txtNamaPlg.requestFocus();
                    }else{
                        insertData();
                    }
                }
            }
        }else if (btnEdit.getText().equals("Edit")){
            editData();
        }

        //*
        //*/
}//GEN-LAST:event_btnEditActionPerformed

    private void txtKdPlgKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKdPlgKeyReleased
        // TODO add your handling code here:      
}//GEN-LAST:event_txtKdPlgKeyReleased

    private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowAllActionPerformed
        // TODO add your handling code here:
        tampilData();
        txtSearch.setText("");
}//GEN-LAST:event_btnShowAllActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
        kosongkanNew();
}//GEN-LAST:event_btnNewActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        tampilTabelSearch();
        kosongkan();
        
}//GEN-LAST:event_btnSearchActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnShowAll;
    private javax.swing.JComboBox cbJk;
    private javax.swing.JComboBox cbSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnAtas;
    private javax.swing.JPanel pnTengah;
    private javax.swing.JScrollPane spPlg;
    private javax.swing.JTable tbPlg;
    private javax.swing.JTextArea txtAlamat;
    private javax.swing.JTextField txtHp;
    private javax.swing.JTextField txtKdPlg;
    private javax.swing.JTextField txtNamaPlg;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtTelp;
    // End of variables declaration//GEN-END:variables


    private void kosongkan(){
        txtKdPlg.setText("");
        txtNamaPlg.setText("");
        cbJk.setSelectedItem("Pria");
        txtTelp.setText("");
        txtHp.setText("");
        txtAlamat.setText("");
        btnEdit.setEnabled(false);
        btnDelete.setEnabled(false);
        btnEdit.setText("Edit");
        btnDelete.setText("Delete");
    }
    private void kosongkanNew(){
        setKdPlg();
        txtNamaPlg.setText("");
        cbJk.setSelectedItem("Pria");
        txtTelp.setText("");
        txtHp.setText("");
        txtAlamat.setText("");
        btnEdit.setText("Save");
        btnDelete.setText("Cancel");
        btnEdit.setEnabled(true);
        btnDelete.setEnabled(true);
    }
    private void tampilData(){
        Object[] Baris={"Kode","Nama"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbPlg.setModel(DftTabMode);

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tplg");
            while (rslt.next()) {                
                String sKdPlg = rslt.getString("kdPlg");
                String sNamaPlg = rslt.getString("nmPlg");                

                String[] dataField = {sKdPlg, sNamaPlg};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }

    private void tampilTabelSearch(){
        
        String srcby = "";
        if(cbSearch.getSelectedItem().toString().equals("Kode Plg")){
            srcby = "kdPlg";
        }else{
            srcby = "nmPlg";
        }

        Object[] Baris={"Kode","Nama"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbPlg.setModel(DftTabMode);

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery(
                    "SELECT * FROM tplg WHERE UPPER(" + srcby +
                    ") like UPPER('%" +
                    txtSearch.getText() + "%')");
            
            while (rslt.next()) {                
                String sKdPlg = rslt.getString("kdPlg");
                String sNamaPlg = rslt.getString("nmPlg");               

                String[] dataField = {sKdPlg, sNamaPlg};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }
    private void deleteData(){
            try {
                int deleting;
                deleting = JOptionPane.showConfirmDialog(this,
                        "Apakah Anda yakin akan menghapus "

                        //+ cbKodeKota.getSelectedItem().toString() +" "
                        +txtNamaPlg.getText() +"?",
                        "Konfirmasi",
                        JOptionPane.YES_NO_OPTION);
                if (deleting == 0){

                    PreparedStatement pStatement = null;
                    String sql = "DELETE FROM tplg " +
                            "WHERE kdPlg=? ";
                    pStatement = conn.prepareStatement(sql);

                    pStatement.setString(1, txtKdPlg.getText());

                    int intTambah = pStatement.executeUpdate();
                    if (intTambah >0){
                        JOptionPane.showMessageDialog(this,
                                "Delete sukses", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);

                    }else {
                        JOptionPane.showMessageDialog(this,
                                "Delete gagal", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);
                    }

                    pStatement.close();

                    kosongkan();
                    tampilData();
                }
            } catch(SQLException e){
                System.out.println("koneksi gagal " + e.toString());
            }
    }
    private boolean isDuplicatePKey(){        
        String pKey = txtKdPlg.getText();
        boolean result = true;
        int row = 0;

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tplg WHERE kdPlg=" +
                    "'" +pKey+ "'");
            while (rslt.next()) {
                row = rslt.getRow();
            }
                if(row > 0){
                    JOptionPane.showMessageDialog(this, "Kode "+pKey+" sudah ada"
                            ,"Peringatan",JOptionPane.WARNING_MESSAGE);
                    result = true;
                }else{
                    result = false;
                }
            System.out.println("row : " + row);
        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
        return result;
    }
    private void insertData(){
        // panggil method koneksi
        //java.sql.Connection conn = new DBConnection().connect();

        java.sql.PreparedStatement pStatement = null;
        String sql = "INSERT INTO tplg " +
                "(kdPlg, nmPlg, jk, alamat, tlp, hp, tgl_insert, tgl_update,user_id) " +
                "VALUES (?,?,?,?,?,?,now(),now(),?)";
        try {
            pStatement = conn.prepareStatement(sql);
            pStatement.setString(1, txtKdPlg.getText());
            pStatement.setString(2, txtNamaPlg.getText());
            String sJk = (String)cbJk.getSelectedItem();
            if(sJk.equals("Pria")){
                pStatement.setString(3, "L");
            }else{
                pStatement.setString(3, "P");
            }
            
            pStatement.setString(4, txtAlamat.getText());
            pStatement.setString(5, txtTelp.getText());
            pStatement.setString(6, txtHp.getText());
            pStatement.setString(7, "admin");

            int intTambah = pStatement.executeUpdate();
            if (intTambah>0){
                JOptionPane.showMessageDialog(this,
                        "Penambahan sukses", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this,
                        "Penambahan gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            pStatement.close();
            //conn.close();

            kosongkan();
            tampilData();

        }
        catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }

    }

     private void editData(){

        try {
            PreparedStatement pStatement = null;
            String sql = "UPDATE tplg " +
                    "SET nmPlg=?, jk=?, alamat=?, tlp=?, hp=?, tgl_update=now() " +
                    "WHERE kdPlg=? ";
            pStatement = conn.prepareStatement(sql);

            pStatement.setString(1, txtNamaPlg.getText());
            String sJk = (String)cbJk.getSelectedItem();
            if(sJk.equals("Pria")){
                pStatement.setString(2, "L");
            }else{
                pStatement.setString(2, "P");
            }           
            pStatement.setString(3, txtAlamat.getText());
            pStatement.setString(4, txtTelp.getText());
            pStatement.setString(5, txtHp.getText());
            pStatement.setString(6, txtKdPlg.getText());

            int intTambah = pStatement.executeUpdate();
            if (intTambah >0){
                JOptionPane.showMessageDialog(this,
                        "Edit sukses", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);

            }else {
                JOptionPane.showMessageDialog(this,
                        "Edit gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }

            pStatement.close();
            kosongkan();
            tampilData();


        } catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }
    }
    private void getDataFromTable(){
                // TODO add your handling code here:
        Object oKdPlg, oNamaPlg, oJk;

        oKdPlg = tbPlg.getValueAt(tbPlg.getSelectedRow(), 0);
        oNamaPlg = tbPlg.getValueAt(tbPlg.getSelectedRow(), 1);


        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tplg WHERE kdPlg=" +
                    "'" +oKdPlg+ "'");
            while (rslt.next()) {
                
                oJk = rslt.getString("jk");
                if(oJk.toString().equals("L")){
                    cbJk.setSelectedItem("Pria");
                }else{
                    cbJk.setSelectedItem("Wanita");
                }
                
                
                txtTelp.setText(rslt.getString("tlp"));
                txtHp.setText(rslt.getString("hp"));
                txtAlamat.setText(rslt.getString("alamat"));
                
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }

        /*
        if(oTest == null){
            oTest = " ";
        }
         *
         */

        txtKdPlg.setText(oKdPlg.toString());
        txtNamaPlg.setText(oNamaPlg.toString());

        btnEdit.setText("Edit");
        btnDelete.setText("Delete");
        
        btnEdit.setEnabled(true);
        btnDelete.setEnabled(true);
    }

    private void setKdPlg(){
        String kdPlg = "";
        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery(
                    "SELECT * FROM tplg");
            //int iNo = 0;
            while (rslt.next()) {
                int row = rslt.getRow();
                kdPlg = rslt.getString("kdPlg");
            }
        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
        if(kdPlg.equals("")){
            kdPlg = "PL00000";
        }

        System.out.println(kdPlg);
        kdPlg = kdPlg.substring(2);
        System.out.println(kdPlg);
        int noUrut;
        noUrut = Integer.parseInt(kdPlg);
        noUrut++;
        java.text.DecimalFormat nft = new java.text.DecimalFormat("#00000.###");
        nft.setDecimalSeparatorAlwaysShown(false);
        System.out.println("PL"+nft.format(noUrut));
        txtKdPlg.setText("PL"+nft.format(noUrut));
    }
}
